<template>
  <div class="article-list">
    <el-card shadow="never">
      <template #header>
        <div class="header">
          <span>文章列表</span>
        </div>
      </template>
      <div class="opt">
        <div class="left">
          <span>文章分类</span>
          <el-select v-model="cateValue" placeholder="请选择分类" size="mini">
            <el-option
              v-for="item in cates"
              :key="item.id"
              :label="item.cate_name"
              :value="item.cate_name">
            </el-option>
          </el-select>
          <span>发布状态</span>
          <el-select v-model="stateValue" placeholder="请选择状态" size="mini">
            <el-option
              v-for="item in states"
              :key="item.id"
              :label="item.state"
              :value="item.state">
            </el-option>
          </el-select>
          <el-button @click="queryData" type="primary" size="small">筛选</el-button>
          <el-button @click="reset" class="reset" size="small">重置</el-button>
        </div>
        <div class="right"><el-button @click="openDialog('add')" size="small" type="primary">发表文章</el-button></div>
      </div>
      <el-table ref="table" :data="list" border style="width: 100%">
        <el-table-column prop="title" label="文章标题"></el-table-column>
        <el-table-column prop="cate_name" label="分类" width="200"></el-table-column>
        <el-table-column prop="pub_date" label="发表时间"></el-table-column>
        <el-table-column prop="state" label="状态"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="obj">
            <el-button @click="openDialog('edit', obj.row.id)" type="primary">修改</el-button>
            <el-button @click="del(obj.row.id)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 发表文章的弹框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="1000px">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="form.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <quill-editor v-model="form.content"></quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <div class="image">
              <img :src="imageUrl" alt="请选择封面" />
            </div>
            <div @click="onUpload" class="opt-file">
              <i class="el-icon-plus"></i>
              <span>选择封面</span>
            </div>
            <input type="file" ref="fileInput" accept="image/*" @change="getFile" style="display: none"/>
          </el-form-item>
          <el-button @click="submit" class="btn" type="primary" size="mini">发布</el-button>
          <el-button @click="temp" class="draft" size="mini">存为草稿</el-button>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import filter from '@/common/filter'
import { getArticleList, getArticleInfo, delArticle, addArticle, updateArticle } from '@/api/article'
import { getCateList } from '@/api/cate'
import { quillEditor } from 'vue-quill-editor'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'article-list-page',
  components: {
    quillEditor
  },
  data () {
    return {
      list: [],
      cates: [],
      states: [],
      pagenum: 1,
      pagesize: 2,
      total: 0,
      cateValue: '',
      stateValue: '',
      tableData: [],
      dialogFormVisible: false,
      dialogType: 'add',
      options: [],
      form: {
        cate_id: null,
        title: '',
        content: '',
        cover_img: null,
        state: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: ['blur', 'change'] },
          { min: 1, max: 30, message: '请输入1~30个字符', trigger: ['blur', 'change'] }
        ],
        cate_name: [{ required: true, message: '请选择分类', trigger: ['blur', 'change'] }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      imageUrl: ''
    }
  },
  computed: {
    dialogTitle () {
      let title = '标题'
      if (this.dialogType === 'add') title = '发表文章'
      if (this.dialogType === 'edit') title = '修改文章'
      return title
    }
  },
  async created () {
    this.initData()
  },
  methods: {
    // 选择器去重
    handleSelect () {
      let resources = this.list
      const temp = {}
      resources = resources.reduce((prev, curv) => {
        if (!temp[curv.cate_name]) {
          temp[curv.cate_name] = true
          prev.push(curv)
        }
        return prev
      }, [])
      this.cates = resources
      let resources2 = this.list
      const temp2 = {}
      resources2 = resources2.reduce((prev, curv) => {
        if (!temp2[curv.state]) {
          temp2[curv.state] = true
          prev.push(curv)
        }
        return prev
      }, [])
      this.states = resources2
    },
    // if (this.cateValue === item.cate_name)
    // if (this.stateValue === item.state)
    queryData () {
      this.tableData = []
      this.list.forEach((item, index) => {
        if ((this.cateValue === item.cate_name) && (this.stateValue === item.state)) {
          this.tableData.push(this.list[index])
          this.list = this.tableData
        }
      })
    },
    reset () {
      this.cateValue = ''
      this.stateValue = ''
    },
    async initData () {
      const res = await getArticleList({
        pagenum: this.pagenum,
        pagesize: this.pagesize,
        cate_id: this.cate_id,
        state: this.state
      })
      res.data.forEach(item => {
        const time = filter.formatDate(item.pub_date)
        this.$set(item, 'pub_date', time)
      })
      this.list = res.data
      this.total = res.total
      this.handleSelect()
      const { data } = await getCateList()
      this.options = data
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.initData()
    },
    handleSizeChange (val) {
      this.pagesize = val
      this.initData()
    },
    async del (id) {
      await delArticle(id)
      this.$message.success('删除文章成功')
      this.initData()
    },
    // 发表文章
    async openDialog (type, id) {
      this.dialogType = type
      this.dialogFormVisible = true
      if (type === 'edit') {
        const res = await getArticleInfo(id)
        this.form = { ...res.data }
      }
    },
    async onUpload () {
      this.$refs.fileInput.click()
    },
    getFile (event) {
      const files = event.target.files
      const filename = files[0].name
      if (filename.lastIndexOf('.') <= 0) {
        return alert('Please add a valid image!')
      }
      const fileReader = new FileReader()
      fileReader.addEventListener('load', () => {
        this.imageUrl = fileReader.result
      })
      fileReader.readAsDataURL(files[0])
      this.image = files[0]
    },
    async loadArticle () {
      this.form.cover_img = this.image
      const fd = new FormData()
      fd.append('title', this.form.title)
      fd.append('cate_id', this.form.cate_id)
      fd.append('content', this.form.content)
      fd.append('state', this.form.state)
      fd.append('cover_img', this.form.cover_img)
      await addArticle(fd)
      this.$router.push('/art-list')
      this.$refs.form.resetFields()
    },
    async submit () {
      this.form.state = '已发布'
      if (this.dialogType === 'add') {
        this.loadArticle()
        this.$message.success('发布文章成功')
      }
      if (this.dialogType === 'edit') {
        this.form.cover_img = this.image
        const fd = new FormData()
        fd.append('title', this.form.title)
        fd.append('cate_id', this.form.cate_id)
        fd.append('content', this.form.content)
        fd.append('state', this.form.state)
        fd.append('cover_img', this.form.cover_img)
        fd.append('id', this.form.id)
        const res = await updateArticle(fd)
        this.$message(res.message)
      }
      this.initData()
      this.dialogFormVisible = false
    },
    async temp () {
      this.form.state = '草稿'
      if (this.dialogType === 'add') {
        this.loadArticle()
        this.$message.success('发布草稿成功')
      }
      if (this.dialogType === 'edit') {
        this.form.cover_img = this.image
        const fd = new FormData()
        fd.append('title', this.form.title)
        fd.append('cate_id', this.form.cate_id)
        fd.append('content', this.form.content)
        fd.append('state', this.form.state)
        fd.append('cover_img', this.form.cover_img)
        fd.append('id', this.form.id)
        const res = await updateArticle(fd)
        this.$message(res.message)
      }
      this.dialogFormVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
    span {
        font-size: 16px;
        color: #131523;
        font-weight: 500;
      }
  }
  .opt {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 72px;
    .left {
      span {
        font-size: 14px;
        color: rgba(0,0,0,0.40);
      }
      .el-select {
        margin-left: 10px;
        margin-right: 10px;
      }
      .reset {
        background-color: #EAECF5;
        color: #0052D9;
        border: 0;
        font-weight: 400;
        &:hover {
          background-color: #F5F6FA;
        }
      }
    }
  }
  .el-dialog {
    .el-form {
    .quill-editor {
      ::v-deep .ql-editor {
        height: 120px;
      }
    }
    .image {
      width: 320px;
      height: 220px;
      background-color: #eee;
      img {
        width: 320px;
        height: 220px;
      }
    }
    .opt-file {
      color: #4F81FF;
      &:hover {
        cursor: pointer;
      }
    }
    .btn {
      margin-left: 80px;
    }
    .draft {
      background-color: #E7E7E7;
    }
  }
  }
}
</style>
